using SheLife.Application.Interfaces;
using SheLife.Domain.Entities;
using SheLife.Infrastructure.Repositories;

namespace SheLife.Application.Services
{
    /// <summary>
    /// 社区帖子服务实现
    /// </summary>
    public class CommunityPostService : ICommunityPostService
    {
        private readonly IUnitOfWork _unitOfWork;

        public CommunityPostService(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public async Task<CommunityPost?> GetCommunityPostByIdAsync(Guid id)
        {
            return await _unitOfWork.CommunityPostRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<CommunityPost>> GetAllCommunityPostsAsync(int page = 1, int pageSize = 20)
        {
            return await _unitOfWork.CommunityPostRepository.GetAllPagedAsync(page, pageSize);
        }

        public async Task<IEnumerable<CommunityPost>> GetCommunityPostsByUserIdAsync(Guid userId, int page = 1, int pageSize = 20)
        {
            return await _unitOfWork.CommunityPostRepository.GetByUserIdPagedAsync(userId, page, pageSize);
        }

        public async Task<IEnumerable<CommunityPost>> GetCommunityPostsByCategoryIdAsync(Guid categoryId, int page = 1, int pageSize = 20)
        {
            return await _unitOfWork.CommunityPostRepository.GetByCategoryIdPagedAsync(categoryId, page, pageSize);
        }

        public async Task<IEnumerable<CommunityPost>> GetCommunityPostsByTagAsync(string tag, int page = 1, int pageSize = 20)
        {
            return await _unitOfWork.CommunityPostRepository.GetByTagPagedAsync(tag, page, pageSize);
        }

        public async Task<IEnumerable<CommunityPost>> GetHotCommunityPostsAsync(int page = 1, int pageSize = 20)
        {
            return await _unitOfWork.CommunityPostRepository.GetHotPostsPagedAsync(page, pageSize);
        }

        public async Task<IEnumerable<CommunityPost>> GetRecommendedCommunityPostsAsync(Guid userId, int page = 1, int pageSize = 20)
        {
            return await _unitOfWork.CommunityPostRepository.GetRecommendedPostsPagedAsync(userId, page, pageSize);
        }

        public async Task<CommunityPost> CreateCommunityPostAsync(Guid userId, Guid categoryId, string title, string content, string? imageUrl = null, List<string>? tags = null)
        {
            var communityPost = new CommunityPost
            {
                Id = Guid.NewGuid(),
                UserId = userId,
                CategoryId = categoryId,
                Title = title,
                Content = content,
                ImageUrl = imageUrl,
                Tags = tags ?? new List<string>(),
                LikeCount = 0,
                CommentCount = 0,
                ViewCount = 0,
                ShareCount = 0,
                IsPinned = false,
                Status = "已发布",
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _unitOfWork.CommunityPostRepository.AddAsync(communityPost);
            await _unitOfWork.SaveChangesAsync();

            return communityPost;
        }

        public async Task<CommunityPost?> UpdateCommunityPostAsync(Guid id, string? title, string? content, string? imageUrl, List<string>? tags)
        {
            var communityPost = await _unitOfWork.CommunityPostRepository.GetByIdAsync(id);
            if (communityPost == null)
                return null;

            if (title != null) communityPost.Title = title;
            if (content != null) communityPost.Content = content;
            if (imageUrl != null) communityPost.ImageUrl = imageUrl;
            if (tags != null) communityPost.Tags = tags;

            communityPost.UpdatedAt = DateTime.UtcNow;

            await _unitOfWork.CommunityPostRepository.UpdateAsync(communityPost);
            await _unitOfWork.SaveChangesAsync();

            return communityPost;
        }

        public async Task<bool> DeleteCommunityPostAsync(Guid id)
        {
            var communityPost = await _unitOfWork.CommunityPostRepository.GetByIdAsync(id);
            if (communityPost == null)
                return false;

            await _unitOfWork.CommunityPostRepository.DeleteAsync(communityPost);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<CommunityPost?> LikeCommunityPostAsync(Guid id, Guid userId)
        {
            var communityPost = await _unitOfWork.CommunityPostRepository.GetByIdAsync(id);
            if (communityPost == null)
                return null;

            // 检查用户是否已经点赞
            var isLiked = await _unitOfWork.CommunityPostLikeRepository.IsUserLikedPostAsync(id, userId);
            if (!isLiked)
            {
                // 添加点赞记录
                var like = new CommunityPostLike
                {
                    Id = Guid.NewGuid(),
                    PostId = id,
                    UserId = userId,
                    CreatedAt = DateTime.UtcNow
                };

                await _unitOfWork.CommunityPostLikeRepository.AddAsync(like);
                
                // 更新帖子点赞数
                communityPost.LikeCount++;
                communityPost.UpdatedAt = DateTime.UtcNow;

                await _unitOfWork.CommunityPostRepository.UpdateAsync(communityPost);
                await _unitOfWork.SaveChangesAsync();
            }

            return communityPost;
        }

        public async Task<CommunityPost?> UnlikeCommunityPostAsync(Guid id, Guid userId)
        {
            var communityPost = await _unitOfWork.CommunityPostRepository.GetByIdAsync(id);
            if (communityPost == null)
                return null;

            // 检查用户是否已经点赞
            var like = await _unitOfWork.CommunityPostLikeRepository.GetUserLikeForPostAsync(id, userId);
            if (like != null)
            {
                // 删除点赞记录
                await _unitOfWork.CommunityPostLikeRepository.DeleteAsync(like);
                
                // 更新帖子点赞数
                communityPost.LikeCount--;
                communityPost.UpdatedAt = DateTime.UtcNow;

                await _unitOfWork.CommunityPostRepository.UpdateAsync(communityPost);
                await _unitOfWork.SaveChangesAsync();
            }

            return communityPost;
        }

        public async Task<CommunityPost?> ViewCommunityPostAsync(Guid id, Guid userId)
        {
            var communityPost = await _unitOfWork.CommunityPostRepository.GetByIdAsync(id);
            if (communityPost == null)
                return null;

            // 添加浏览记录
            var view = new CommunityPostView
            {
                Id = Guid.NewGuid(),
                PostId = id,
                UserId = userId,
                CreatedAt = DateTime.UtcNow
            };

            await _unitOfWork.CommunityPostViewRepository.AddAsync(view);
            
            // 更新帖子浏览数
            communityPost.ViewCount++;
            communityPost.UpdatedAt = DateTime.UtcNow;

            await _unitOfWork.CommunityPostRepository.UpdateAsync(communityPost);
            await _unitOfWork.SaveChangesAsync();

            return communityPost;
        }

        public async Task<CommunityPost?> PinCommunityPostAsync(Guid id)
        {
            var communityPost = await _communityPostRepository.GetByIdAsync(id);
            if (communityPost == null)
                return null;

            communityPost.IsPinned = true;
            communityPost.UpdatedAt = DateTime.UtcNow;

            await _communityPostRepository.UpdateAsync(communityPost);
            await _unitOfWork.SaveChangesAsync();

            return communityPost;
        }

        public async Task<CommunityPost?> UnpinCommunityPostAsync(Guid id)
        {
            var communityPost = await _communityPostRepository.GetByIdAsync(id);
            if (communityPost == null)
                return null;

            communityPost.IsPinned = false;
            communityPost.UpdatedAt = DateTime.UtcNow;

            await _communityPostRepository.UpdateAsync(communityPost);
            await _unitOfWork.SaveChangesAsync();

            return communityPost;
        }

        public async Task<CommunityPost?> SetCommunityPostStatusAsync(Guid id, string status)
        {
            var communityPost = await _communityPostRepository.GetByIdAsync(id);
            if (communityPost == null)
                return null;

            communityPost.Status = status;
            communityPost.UpdatedAt = DateTime.UtcNow;

            await _communityPostRepository.UpdateAsync(communityPost);
            await _unitOfWork.SaveChangesAsync();

            return communityPost;
        }
    }

    /// <summary>
    /// 社区帖子评论服务实现
    /// </summary>
    public class CommunityPostCommentService : ICommunityPostCommentService
    {
        private readonly ICommunityPostCommentRepository _communityPostCommentRepository;
        private readonly ICommunityPostLikeRepository _communityPostLikeRepository;
        private readonly IUnitOfWork _unitOfWork;

        public CommunityPostCommentService(
            ICommunityPostCommentRepository communityPostCommentRepository,
            ICommunityPostLikeRepository communityPostLikeRepository,
            IUnitOfWork unitOfWork)
        {
            _communityPostCommentRepository = communityPostCommentRepository;
            _communityPostLikeRepository = communityPostLikeRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<CommunityPostComment?> GetCommunityPostCommentByIdAsync(Guid id)
        {
            return await _communityPostCommentRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<CommunityPostComment>> GetCommunityPostCommentsByPostIdAsync(Guid postId, int page = 1, int pageSize = 20)
        {
            return await _communityPostCommentRepository.GetByPostIdPagedAsync(postId, page, pageSize);
        }

        public async Task<IEnumerable<CommunityPostComment>> GetCommunityPostCommentsByUserIdAsync(Guid userId, int page = 1, int pageSize = 20)
        {
            return await _communityPostCommentRepository.GetByUserIdPagedAsync(userId, page, pageSize);
        }

        public async Task<IEnumerable<CommunityPostComment>> GetCommunityPostCommentsByParentIdAsync(Guid parentId, int page = 1, int pageSize = 20)
        {
            return await _communityPostCommentRepository.GetByParentIdPagedAsync(parentId, page, pageSize);
        }

        public async Task<CommunityPostComment> CreateCommunityPostCommentAsync(Guid postId, Guid userId, string content, Guid? parentId = null)
        {
            var communityPostComment = new CommunityPostComment
            {
                Id = Guid.NewGuid(),
                PostId = postId,
                UserId = userId,
                ParentId = parentId,
                Content = content,
                LikeCount = 0,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _communityPostCommentRepository.AddAsync(communityPostComment);
            await _unitOfWork.SaveChangesAsync();

            return communityPostComment;
        }

        public async Task<CommunityPostComment?> UpdateCommunityPostCommentAsync(Guid id, string content)
        {
            var communityPostComment = await _communityPostCommentRepository.GetByIdAsync(id);
            if (communityPostComment == null)
                return null;

            communityPostComment.Content = content;
            communityPostComment.UpdatedAt = DateTime.UtcNow;

            await _communityPostCommentRepository.UpdateAsync(communityPostComment);
            await _unitOfWork.SaveChangesAsync();

            return communityPostComment;
        }

        public async Task<bool> DeleteCommunityPostCommentAsync(Guid id)
        {
            var communityPostComment = await _communityPostCommentRepository.GetByIdAsync(id);
            if (communityPostComment == null)
                return false;

            await _communityPostCommentRepository.DeleteAsync(communityPostComment);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<CommunityPostComment?> LikeCommunityPostCommentAsync(Guid id, Guid userId)
        {
            var communityPostComment = await _communityPostCommentRepository.GetByIdAsync(id);
            if (communityPostComment == null)
                return null;

            // 检查用户是否已经点赞
            var isLiked = await _communityPostLikeRepository.IsUserLikedCommentAsync(id, userId);
            if (!isLiked)
            {
                // 添加点赞记录
                var like = new CommunityPostLike
                {
                    Id = Guid.NewGuid(),
                    CommentId = id,
                    UserId = userId,
                    CreatedAt = DateTime.UtcNow
                };

                await _communityPostLikeRepository.AddAsync(like);
                
                // 更新评论点赞数
                communityPostComment.LikeCount++;
                communityPostComment.UpdatedAt = DateTime.UtcNow;

                await _communityPostCommentRepository.UpdateAsync(communityPostComment);
                await _unitOfWork.SaveChangesAsync();
            }

            return communityPostComment;
        }

        public async Task<CommunityPostComment?> UnlikeCommunityPostCommentAsync(Guid id, Guid userId)
        {
            var communityPostComment = await _communityPostCommentRepository.GetByIdAsync(id);
            if (communityPostComment == null)
                return null;

            // 检查用户是否已经点赞
            var like = await _communityPostLikeRepository.GetUserLikeForCommentAsync(id, userId);
            if (like != null)
            {
                // 删除点赞记录
                await _communityPostLikeRepository.DeleteAsync(like);
                
                // 更新评论点赞数
                communityPostComment.LikeCount--;
                communityPostComment.UpdatedAt = DateTime.UtcNow;

                await _communityPostCommentRepository.UpdateAsync(communityPostComment);
                await _unitOfWork.SaveChangesAsync();
            }

            return communityPostComment;
        }
    }

    /// <summary>
    /// 社区帖子点赞服务实现
    /// </summary>
    public class CommunityPostLikeService : ICommunityPostLikeService
    {
        private readonly ICommunityPostLikeRepository _communityPostLikeRepository;
        private readonly IUnitOfWork _unitOfWork;

        public CommunityPostLikeService(ICommunityPostLikeRepository communityPostLikeRepository, IUnitOfWork unitOfWork)
        {
            _communityPostLikeRepository = communityPostLikeRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<CommunityPostLike?> GetCommunityPostLikeByIdAsync(Guid id)
        {
            return await _communityPostLikeRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<CommunityPostLike>> GetCommunityPostLikesByPostIdAsync(Guid postId, int page = 1, int pageSize = 20)
        {
            return await _communityPostLikeRepository.GetByPostIdPagedAsync(postId, page, pageSize);
        }

        public async Task<IEnumerable<CommunityPostLike>> GetCommunityPostLikesByUserIdAsync(Guid userId, int page = 1, int pageSize = 20)
        {
            return await _communityPostLikeRepository.GetByUserIdPagedAsync(userId, page, pageSize);
        }

        public async Task<CommunityPostLike> CreateCommunityPostLikeAsync(Guid postId, Guid userId)
        {
            var communityPostLike = new CommunityPostLike
            {
                Id = Guid.NewGuid(),
                PostId = postId,
                UserId = userId,
                CreatedAt = DateTime.UtcNow
            };

            await _communityPostLikeRepository.AddAsync(communityPostLike);
            await _unitOfWork.SaveChangesAsync();

            return communityPostLike;
        }

        public async Task<bool> DeleteCommunityPostLikeAsync(Guid id)
        {
            var communityPostLike = await _communityPostLikeRepository.GetByIdAsync(id);
            if (communityPostLike == null)
                return false;

            await _communityPostLikeRepository.DeleteAsync(communityPostLike);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> IsUserLikedPostAsync(Guid postId, Guid userId)
        {
            return await _communityPostLikeRepository.IsUserLikedPostAsync(postId, userId);
        }
    }

    /// <summary>
    /// 社区帖子收藏服务实现
    /// </summary>
    public class CommunityPostFavoriteService : ICommunityPostFavoriteService
    {
        private readonly ICommunityPostFavoriteRepository _communityPostFavoriteRepository;
        private readonly IUnitOfWork _unitOfWork;

        public CommunityPostFavoriteService(ICommunityPostFavoriteRepository communityPostFavoriteRepository, IUnitOfWork unitOfWork)
        {
            _communityPostFavoriteRepository = communityPostFavoriteRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<CommunityPostFavorite?> GetCommunityPostFavoriteByIdAsync(Guid id)
        {
            return await _communityPostFavoriteRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<CommunityPostFavorite>> GetCommunityPostFavoritesByUserIdAsync(Guid userId, int page = 1, int pageSize = 20)
        {
            return await _communityPostFavoriteRepository.GetByUserIdPagedAsync(userId, page, pageSize);
        }

        public async Task<IEnumerable<CommunityPostFavorite>> GetCommunityPostFavoritesByPostIdAsync(Guid postId, int page = 1, int pageSize = 20)
        {
            return await _communityPostFavoriteRepository.GetByPostIdPagedAsync(postId, page, pageSize);
        }

        public async Task<CommunityPostFavorite> CreateCommunityPostFavoriteAsync(Guid postId, Guid userId, string? notes = null)
        {
            var communityPostFavorite = new CommunityPostFavorite
            {
                Id = Guid.NewGuid(),
                PostId = postId,
                UserId = userId,
                Notes = notes,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _communityPostFavoriteRepository.AddAsync(communityPostFavorite);
            await _unitOfWork.SaveChangesAsync();

            return communityPostFavorite;
        }

        public async Task<CommunityPostFavorite?> UpdateCommunityPostFavoriteAsync(Guid id, string? notes)
        {
            var communityPostFavorite = await _communityPostFavoriteRepository.GetByIdAsync(id);
            if (communityPostFavorite == null)
                return null;

            if (notes != null) communityPostFavorite.Notes = notes;

            communityPostFavorite.UpdatedAt = DateTime.UtcNow;

            await _communityPostFavoriteRepository.UpdateAsync(communityPostFavorite);
            await _unitOfWork.SaveChangesAsync();

            return communityPostFavorite;
        }

        public async Task<bool> DeleteCommunityPostFavoriteAsync(Guid id)
        {
            var communityPostFavorite = await _communityPostFavoriteRepository.GetByIdAsync(id);
            if (communityPostFavorite == null)
                return false;

            await _communityPostFavoriteRepository.DeleteAsync(communityPostFavorite);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> IsUserFavoritedPostAsync(Guid postId, Guid userId)
        {
            return await _communityPostFavoriteRepository.IsUserFavoritedPostAsync(postId, userId);
        }
    }

    /// <summary>
    /// 社区帖子分类服务实现
    /// </summary>
    public class CommunityPostCategoryService : ICommunityPostCategoryService
    {
        private readonly ICommunityPostCategoryRepository _communityPostCategoryRepository;
        private readonly IUnitOfWork _unitOfWork;

        public CommunityPostCategoryService(ICommunityPostCategoryRepository communityPostCategoryRepository, IUnitOfWork unitOfWork)
        {
            _communityPostCategoryRepository = communityPostCategoryRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<CommunityPostCategory?> GetCommunityPostCategoryByIdAsync(Guid id)
        {
            return await _communityPostCategoryRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<CommunityPostCategory>> GetAllCommunityPostCategoriesAsync()
        {
            return await _communityPostCategoryRepository.GetAllAsync();
        }

        public async Task<CommunityPostCategory> CreateCommunityPostCategoryAsync(string name, string description, string? icon = null, int order = 0)
        {
            var communityPostCategory = new CommunityPostCategory
            {
                Id = Guid.NewGuid(),
                Name = name,
                Description = description,
                Icon = icon,
                Order = order,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _communityPostCategoryRepository.AddAsync(communityPostCategory);
            await _unitOfWork.SaveChangesAsync();

            return communityPostCategory;
        }

        public async Task<CommunityPostCategory?> UpdateCommunityPostCategoryAsync(Guid id, string? name, string? description, string? icon, int? order)
        {
            var communityPostCategory = await _communityPostCategoryRepository.GetByIdAsync(id);
            if (communityPostCategory == null)
                return null;

            if (name != null) communityPostCategory.Name = name;
            if (description != null) communityPostCategory.Description = description;
            if (icon != null) communityPostCategory.Icon = icon;
            if (order.HasValue) communityPostCategory.Order = order.Value;

            communityPostCategory.UpdatedAt = DateTime.UtcNow;

            await _communityPostCategoryRepository.UpdateAsync(communityPostCategory);
            await _unitOfWork.SaveChangesAsync();

            return communityPostCategory;
        }

        public async Task<bool> DeleteCommunityPostCategoryAsync(Guid id)
        {
            var communityPostCategory = await _communityPostCategoryRepository.GetByIdAsync(id);
            if (communityPostCategory == null)
                return false;

            await _communityPostCategoryRepository.DeleteAsync(communityPostCategory);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }
    }

    /// <summary>
    /// 社区帖子标签服务实现
    /// </summary>
    public class CommunityPostTagService : ICommunityPostTagService
    {
        private readonly ICommunityPostTagRepository _communityPostTagRepository;
        private readonly IUnitOfWork _unitOfWork;

        public CommunityPostTagService(ICommunityPostTagRepository communityPostTagRepository, IUnitOfWork unitOfWork)
        {
            _communityPostTagRepository = communityPostTagRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<CommunityPostTag?> GetCommunityPostTagByIdAsync(Guid id)
        {
            return await _communityPostTagRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<CommunityPostTag>> GetAllCommunityPostTagsAsync()
        {
            return await _communityPostTagRepository.GetAllAsync();
        }

        public async Task<IEnumerable<CommunityPostTag>> GetPopularCommunityPostTagsAsync(int count = 20)
        {
            return await _communityPostTagRepository.GetPopularTagsAsync(count);
        }

        public async Task<CommunityPostTag> CreateCommunityPostTagAsync(string name, string? description = null, string? color = null)
        {
            var communityPostTag = new CommunityPostTag
            {
                Id = Guid.NewGuid(),
                Name = name,
                Description = description,
                Color = color,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _communityPostTagRepository.AddAsync(communityPostTag);
            await _unitOfWork.SaveChangesAsync();

            return communityPostTag;
        }

        public async Task<CommunityPostTag?> UpdateCommunityPostTagAsync(Guid id, string? name, string? description, string? color)
        {
            var communityPostTag = await _communityPostTagRepository.GetByIdAsync(id);
            if (communityPostTag == null)
                return null;

            if (name != null) communityPostTag.Name = name;
            if (description != null) communityPostTag.Description = description;
            if (color != null) communityPostTag.Color = color;

            communityPostTag.UpdatedAt = DateTime.UtcNow;

            await _communityPostTagRepository.UpdateAsync(communityPostTag);
            await _unitOfWork.SaveChangesAsync();

            return communityPostTag;
        }

        public async Task<bool> DeleteCommunityPostTagAsync(Guid id)
        {
            var communityPostTag = await _communityPostTagRepository.GetByIdAsync(id);
            if (communityPostTag == null)
                return false;

            await _communityPostTagRepository.DeleteAsync(communityPostTag);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }
    }

    /// <summary>
    /// 社区帖子报告服务实现
    /// </summary>
    public class CommunityPostReportService : ICommunityPostReportService
    {
        private readonly ICommunityPostReportRepository _communityPostReportRepository;
        private readonly IUnitOfWork _unitOfWork;

        public CommunityPostReportService(ICommunityPostReportRepository communityPostReportRepository, IUnitOfWork unitOfWork)
        {
            _communityPostReportRepository = communityPostReportRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<CommunityPostReport?> GetCommunityPostReportByIdAsync(Guid id)
        {
            return await _communityPostReportRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<CommunityPostReport>> GetCommunityPostReportsByPostIdAsync(Guid postId)
        {
            return await _communityPostReportRepository.GetByPostIdAsync(postId);
        }

        public async Task<IEnumerable<CommunityPostReport>> GetCommunityPostReportsByUserIdAsync(Guid userId)
        {
            return await _communityPostReportRepository.GetByUserIdAsync(userId);
        }

        public async Task<IEnumerable<CommunityPostReport>> GetCommunityPostReportsByStatusAsync(string status)
        {
            return await _communityPostReportRepository.GetByStatusAsync(status);
        }

        public async Task<CommunityPostReport> CreateCommunityPostReportAsync(Guid postId, Guid userId, string reason, string? description = null)
        {
            var communityPostReport = new CommunityPostReport
            {
                Id = Guid.NewGuid(),
                PostId = postId,
                UserId = userId,
                Reason = reason,
                Description = description,
                Status = "待处理",
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            await _communityPostReportRepository.AddAsync(communityPostReport);
            await _unitOfWork.SaveChangesAsync();

            return communityPostReport;
        }

        public async Task<CommunityPostReport?> UpdateCommunityPostReportAsync(Guid id, string? status, string? description)
        {
            var communityPostReport = await _communityPostReportRepository.GetByIdAsync(id);
            if (communityPostReport == null)
                return null;

            if (status != null) communityPostReport.Status = status;
            if (description != null) communityPostReport.Description = description;

            communityPostReport.UpdatedAt = DateTime.UtcNow;

            await _communityPostReportRepository.UpdateAsync(communityPostReport);
            await _unitOfWork.SaveChangesAsync();

            return communityPostReport;
        }

        public async Task<bool> DeleteCommunityPostReportAsync(Guid id)
        {
            var communityPostReport = await _communityPostReportRepository.GetByIdAsync(id);
            if (communityPostReport == null)
                return false;

            await _communityPostReportRepository.DeleteAsync(communityPostReport);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<CommunityPostReport?> HandleCommunityPostReportAsync(Guid id, string status, string? handlingNotes = null)
        {
            var communityPostReport = await _communityPostReportRepository.GetByIdAsync(id);
            if (communityPostReport == null)
                return null;

            communityPostReport.Status = status;
            communityPostReport.HandlingNotes = handlingNotes;
            communityPostReport.HandledAt = DateTime.UtcNow;
            communityPostReport.UpdatedAt = DateTime.UtcNow;

            await _communityPostReportRepository.UpdateAsync(communityPostReport);
            await _unitOfWork.SaveChangesAsync();

            return communityPostReport;
        }
    }

    /// <summary>
    /// 社区帖子浏览记录服务实现
    /// </summary>
    public class CommunityPostViewService : ICommunityPostViewService
    {
        private readonly ICommunityPostViewRepository _communityPostViewRepository;
        private readonly IUnitOfWork _unitOfWork;

        public CommunityPostViewService(ICommunityPostViewRepository communityPostViewRepository, IUnitOfWork unitOfWork)
        {
            _communityPostViewRepository = communityPostViewRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<CommunityPostView?> GetCommunityPostViewByIdAsync(Guid id)
        {
            return await _communityPostViewRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<CommunityPostView>> GetCommunityPostViewsByPostIdAsync(Guid postId, int page = 1, int pageSize = 20)
        {
            return await _communityPostViewRepository.GetByPostIdPagedAsync(postId, page, pageSize);
        }

        public async Task<IEnumerable<CommunityPostView>> GetCommunityPostViewsByUserIdAsync(Guid userId, int page = 1, int pageSize = 20)
        {
            return await _communityPostViewRepository.GetByUserIdPagedAsync(userId, page, pageSize);
        }

        public async Task<CommunityPostView> CreateCommunityPostViewAsync(Guid postId, Guid userId)
        {
            var communityPostView = new CommunityPostView
            {
                Id = Guid.NewGuid(),
                PostId = postId,
                UserId = userId,
                CreatedAt = DateTime.UtcNow
            };

            await _communityPostViewRepository.AddAsync(communityPostView);
            await _unitOfWork.SaveChangesAsync();

            return communityPostView;
        }

        public async Task<bool> DeleteCommunityPostViewAsync(Guid id)
        {
            var communityPostView = await _communityPostViewRepository.GetByIdAsync(id);
            if (communityPostView == null)
                return false;

            await _communityPostViewRepository.DeleteAsync(communityPostView);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<Dictionary<string, object>> GetPostViewStatisticsAsync(Guid postId)
        {
            var endDate = DateTime.UtcNow;
            var startDate = endDate.AddDays(-30);

            var views = await _communityPostViewRepository.GetByPostIdAndDateRangeAsync(postId, startDate, endDate);

            var statistics = new Dictionary<string, object>
            {
                ["TotalViews"] = views.Count(),
                ["DailyViews"] = views.GroupBy(v => v.CreatedAt.Date)
                                      .ToDictionary(g => g.Key.ToString("yyyy-MM-dd"), g => g.Count()),
                ["UniqueUsers"] = views.Select(v => v.UserId).Distinct().Count()
            };

            return statistics;
        }
    }

    /// <summary>
    /// 社区帖子分享服务实现
    /// </summary>
    public class CommunityPostShareService : ICommunityPostShareService
    {
        private readonly ICommunityPostShareRepository _communityPostShareRepository;
        private readonly IUnitOfWork _unitOfWork;

        public CommunityPostShareService(ICommunityPostShareRepository communityPostShareRepository, IUnitOfWork unitOfWork)
        {
            _communityPostShareRepository = communityPostShareRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<CommunityPostShare?> GetCommunityPostShareByIdAsync(Guid id)
        {
            return await _communityPostShareRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<CommunityPostShare>> GetCommunityPostSharesByPostIdAsync(Guid postId)
        {
            return await _communityPostShareRepository.GetByPostIdAsync(postId);
        }

        public async Task<IEnumerable<CommunityPostShare>> GetCommunityPostSharesByUserIdAsync(Guid userId)
        {
            return await _communityPostShareRepository.GetByUserIdAsync(userId);
        }

        public async Task<CommunityPostShare> CreateCommunityPostShareAsync(Guid postId, Guid userId, string platform)
        {
            var communityPostShare = new CommunityPostShare
            {
                Id = Guid.NewGuid(),
                PostId = postId,
                UserId = userId,
                Platform = platform,
                CreatedAt = DateTime.UtcNow
            };

            await _communityPostShareRepository.AddAsync(communityPostShare);
            await _unitOfWork.SaveChangesAsync();

            return communityPostShare;
        }

        public async Task<bool> DeleteCommunityPostShareAsync(Guid id)
        {
            var communityPostShare = await _communityPostShareRepository.GetByIdAsync(id);
            if (communityPostShare == null)
                return false;

            await _communityPostShareRepository.DeleteAsync(communityPostShare);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<Dictionary<string, object>> GetPostShareStatisticsAsync(Guid postId)
        {
            var endDate = DateTime.UtcNow;
            var startDate = endDate.AddDays(-30);

            var shares = await _communityPostShareRepository.GetByPostIdAndDateRangeAsync(postId, startDate, endDate);

            var statistics = new Dictionary<string, object>
            {
                ["TotalShares"] = shares.Count(),
                ["DailyShares"] = shares.GroupBy(s => s.CreatedAt.Date)
                                       .ToDictionary(g => g.Key.ToString("yyyy-MM-dd"), g => g.Count()),
                ["SharesByPlatform"] = shares.GroupBy(s => s.Platform)
                                            .ToDictionary(g => g.Key, g => g.Count())
            };

            return statistics;
        }
    }

    /// <summary>
    /// 社区用户关注服务实现
    /// </summary>
    public class CommunityUserFollowService : ICommunityUserFollowService
    {
        private readonly ICommunityUserFollowRepository _communityUserFollowRepository;
        private readonly IUnitOfWork _unitOfWork;

        public CommunityUserFollowService(ICommunityUserFollowRepository communityUserFollowRepository, IUnitOfWork unitOfWork)
        {
            _communityUserFollowRepository = communityUserFollowRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<CommunityUserFollow?> GetCommunityUserFollowByIdAsync(Guid id)
        {
            return await _communityUserFollowRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<CommunityUserFollow>> GetCommunityUserFollowsByUserIdAsync(Guid userId)
        {
            return await _communityUserFollowRepository.GetByUserIdAsync(userId);
        }

        public async Task<IEnumerable<CommunityUserFollow>> GetCommunityUserFollowsByFollowedUserIdAsync(Guid followedUserId)
        {
            return await _communityUserFollowRepository.GetByFollowedUserIdAsync(followedUserId);
        }

        public async Task<CommunityUserFollow> CreateCommunityUserFollowAsync(Guid userId, Guid followedUserId)
        {
            var communityUserFollow = new CommunityUserFollow
            {
                Id = Guid.NewGuid(),
                UserId = userId,
                FollowedUserId = followedUserId,
                CreatedAt = DateTime.UtcNow
            };

            await _communityUserFollowRepository.AddAsync(communityUserFollow);
            await _unitOfWork.SaveChangesAsync();

            return communityUserFollow;
        }

        public async Task<bool> DeleteCommunityUserFollowAsync(Guid id)
        {
            var communityUserFollow = await _communityUserFollowRepository.GetByIdAsync(id);
            if (communityUserFollow == null)
                return false;

            await _communityUserFollowRepository.DeleteAsync(communityUserFollow);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> IsUserFollowingUserAsync(Guid userId, Guid followedUserId)
        {
            return await _communityUserFollowRepository.IsUserFollowingUserAsync(userId, followedUserId);
        }
    }

    /// <summary>
    /// 社区用户黑名单服务实现
    /// </summary>
    public class CommunityUserBlockService : ICommunityUserBlockService
    {
        private readonly ICommunityUserBlockRepository _communityUserBlockRepository;
        private readonly IUnitOfWork _unitOfWork;

        public CommunityUserBlockService(ICommunityUserBlockRepository communityUserBlockRepository, IUnitOfWork unitOfWork)
        {
            _communityUserBlockRepository = communityUserBlockRepository;
            _unitOfWork = unitOfWork;
        }

        public async Task<CommunityUserBlock?> GetCommunityUserBlockByIdAsync(Guid id)
        {
            return await _communityUserBlockRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<CommunityUserBlock>> GetCommunityUserBlocksByUserIdAsync(Guid userId)
        {
            return await _communityUserBlockRepository.GetByUserIdAsync(userId);
        }

        public async Task<IEnumerable<CommunityUserBlock>> GetCommunityUserBlocksByBlockedUserIdAsync(Guid blockedUserId)
        {
            return await _communityUserBlockRepository.GetByBlockedUserIdAsync(blockedUserId);
        }

        public async Task<CommunityUserBlock> CreateCommunityUserBlockAsync(Guid userId, Guid blockedUserId, string? reason = null)
        {
            var communityUserBlock = new CommunityUserBlock
            {
                Id = Guid.NewGuid(),
                UserId = userId,
                BlockedUserId = blockedUserId,
                Reason = reason,
                CreatedAt = DateTime.UtcNow
            };

            await _communityUserBlockRepository.AddAsync(communityUserBlock);
            await _unitOfWork.SaveChangesAsync();

            return communityUserBlock;
        }

        public async Task<bool> DeleteCommunityUserBlockAsync(Guid id)
        {
            var communityUserBlock = await _communityUserBlockRepository.GetByIdAsync(id);
            if (communityUserBlock == null)
                return false;

            await _communityUserBlockRepository.DeleteAsync(communityUserBlock);
            await _unitOfWork.SaveChangesAsync();

            return true;
        }

        public async Task<bool> IsUserBlockingUserAsync(Guid userId, Guid blockedUserId)
        {
            return await _communityUserBlockRepository.IsUserBlockingUserAsync(userId, blockedUserId);
        }
    }

    /// <summary>
    /// 社区统计服务实现
    /// </summary>
    public class CommunityStatisticsService : ICommunityStatisticsService
    {
        private readonly ICommunityPostRepository _communityPostRepository;
        private readonly ICommunityPostCommentRepository _communityPostCommentRepository;
        private readonly ICommunityPostLikeRepository _communityPostLikeRepository;
        private readonly ICommunityPostViewRepository _communityPostViewRepository;
        private readonly ICommunityPostShareRepository _communityPostShareRepository;
        private readonly ICommunityPostCategoryRepository _communityPostCategoryRepository;
        private readonly ICommunityPostTagRepository _communityPostTagRepository;

        public CommunityStatisticsService(
            ICommunityPostRepository communityPostRepository,
            ICommunityPostCommentRepository communityPostCommentRepository,
            ICommunityPostLikeRepository communityPostLikeRepository,
            ICommunityPostViewRepository communityPostViewRepository,
            ICommunityPostShareRepository communityPostShareRepository,
            ICommunityPostCategoryRepository communityPostCategoryRepository,
            ICommunityPostTagRepository communityPostTagRepository)
        {
            _communityPostRepository = communityPostRepository;
            _communityPostCommentRepository = communityPostCommentRepository;
            _communityPostLikeRepository = communityPostLikeRepository;
            _communityPostViewRepository = communityPostViewRepository;
            _communityPostShareRepository = communityPostShareRepository;
            _communityPostCategoryRepository = communityPostCategoryRepository;
            _communityPostTagRepository = communityPostTagRepository;
        }

        public async Task<Dictionary<string, object>> GetCommunityStatisticsAsync()
        {
            var totalPosts = await _communityPostRepository.GetTotalCountAsync();
            var totalComments = await _communityPostCommentRepository.GetTotalCountAsync();
            var totalLikes = await _communityPostLikeRepository.GetTotalCountAsync();
            var totalViews = await _communityPostViewRepository.GetTotalCountAsync();
            var totalShares = await _communityPostShareRepository.GetTotalCountAsync();

            var statistics = new Dictionary<string, object>
            {
                ["TotalPosts"] = totalPosts,
                ["TotalComments"] = totalComments,
                ["TotalLikes"] = totalLikes,
                ["TotalViews"] = totalViews,
                ["TotalShares"] = totalShares,
                ["AvgLikesPerPost"] = totalPosts > 0 ? (double)totalLikes / totalPosts : 0,
                ["AvgCommentsPerPost"] = totalPosts > 0 ? (double)totalComments / totalPosts : 0
            };

            return statistics;
        }

        public async Task<Dictionary<string, object>> GetPostStatisticsAsync(int days = 30)
        {
            var endDate = DateTime.UtcNow;
            var startDate = endDate.AddDays(-days);

            var posts = await _communityPostRepository.GetByDateRangeAsync(startDate, endDate);
            var comments = await _communityPostCommentRepository.GetByDateRangeAsync(startDate, endDate);
            var likes = await _communityPostLikeRepository.GetByDateRangeAsync(startDate, endDate);
            var views = await _communityPostViewRepository.GetByDateRangeAsync(startDate, endDate);
            var shares = await _communityPostShareRepository.GetByDateRangeAsync(startDate, endDate);

            var statistics = new Dictionary<string, object>
            {
                ["PostsCreated"] = posts.Count(),
                ["CommentsCreated"] = comments.Count(),
                ["LikesCreated"] = likes.Count(),
                ["ViewsCreated"] = views.Count(),
                ["SharesCreated"] = shares.Count(),
                ["DailyPosts"] = posts.GroupBy(p => p.CreatedAt.Date)
                                      .ToDictionary(g => g.Key.ToString("yyyy-MM-dd"), g => g.Count()),
                ["DailyComments"] = comments.GroupBy(c => c.CreatedAt.Date)
                                          .ToDictionary(g => g.Key.ToString("yyyy-MM-dd"), g => g.Count()),
                ["DailyLikes"] = likes.GroupBy(l => l.CreatedAt.Date)
                                    .ToDictionary(g => g.Key.ToString("yyyy-MM-dd"), g => g.Count()),
                ["DailyViews"] = views.GroupBy(v => v.CreatedAt.Date)
                                    .ToDictionary(g => g.Key.ToString("yyyy-MM-dd"), g => g.Count()),
                ["DailyShares"] = shares.GroupBy(s => s.CreatedAt.Date)
                                      .ToDictionary(g => g.Key.ToString("yyyy-MM-dd"), g => g.Count())
            };

            return statistics;
        }

        public async Task<Dictionary<string, object>> GetUserStatisticsAsync(int days = 30)
        {
            var endDate = DateTime.UtcNow;
            var startDate = endDate.AddDays(-days);

            var posts = await _communityPostRepository.GetByDateRangeAsync(startDate, endDate);
            var comments = await _communityPostCommentRepository.GetByDateRangeAsync(startDate, endDate);
            var likes = await _communityPostLikeRepository.GetByDateRangeAsync(startDate, endDate);

            var statistics = new Dictionary<string, object>
            {
                ["ActivePosters"] = posts.Select(p => p.UserId).Distinct().Count(),
                ["ActiveCommenters"] = comments.Select(c => c.UserId).Distinct().Count(),
                ["ActiveLikers"] = likes.Select(l => l.UserId).Distinct().Count(),
                ["TopPosters"] = posts.GroupBy(p => p.UserId)
                                     .OrderByDescending(g => g.Count())
                                     .Take(10)
                                     .ToDictionary(g => g.Key.ToString(), g => g.Count()),
                ["TopCommenters"] = comments.GroupBy(c => c.UserId)
                                          .OrderByDescending(g => g.Count())
                                          .Take(10)
                                          .ToDictionary(g => g.Key.ToString(), g => g.Count()),
                ["TopLikers"] = likes.GroupBy(l => l.UserId)
                                   .OrderByDescending(g => g.Count())
                                   .Take(10)
                                   .ToDictionary(g => g.Key.ToString(), g => g.Count())
            };

            return statistics;
        }

        public async Task<Dictionary<string, object>> GetCategoryStatisticsAsync()
        {
            var categories = await _communityPostCategoryRepository.GetAllAsync();
            var posts = await _communityPostRepository.GetAllAsync();

            var statistics = new Dictionary<string, object>
            {
                ["TotalCategories"] = categories.Count(),
                ["CategoriesWithPosts"] = categories.Count(c => posts.Any(p => p.CategoryId == c.Id)),
                ["PostsByCategory"] = posts.GroupBy(p => p.CategoryId)
                                          .ToDictionary(g => g.Key.ToString(), g => g.Count())
            };

            return statistics;
        }

        public async Task<Dictionary<string, object>> GetTagStatisticsAsync()
        {
            var tags = await _communityPostTagRepository.GetAllAsync();
            var posts = await _communityPostRepository.GetAllAsync();

            var tagCounts = new Dictionary<string, int>();
            foreach (var post in posts)
            {
                foreach (var tag in post.Tags)
                {
                    if (tagCounts.ContainsKey(tag))
                        tagCounts[tag]++;
                    else
                        tagCounts[tag] = 1;
                }
            }

            var statistics = new Dictionary<string, object>
            {
                ["TotalTags"] = tags.Count(),
                ["TagsUsedInPosts"] = tagCounts.Count,
                ["TopTags"] = tagCounts.OrderByDescending(t => t.Value)
                                      .Take(20)
                                      .ToDictionary(t => t.Key, t => t.Value)
            };

            return statistics;
        }
    }
}